from rest_framework import permissions

class IsAdminUserOrReadCreateOnly(permissions.BasePermission):
    """
    自定义权限类：
    - 管理员用户(role=1)可以执行所有操作
    - 非管理员用户只能查看和创建，不能修改和删除
    """
    
    def has_permission(self, request, view):
        # 允许所有用户进行GET和POST请求
        if request.method in ['GET', 'HEAD', 'OPTIONS', 'POST']:
            return True
            
        # 检查是否为管理员用户
        return request.user and hasattr(request.user, 'role') and request.user.role == 1
        
    def has_object_permission(self, request, view, obj):
        # 允许所有用户进行GET请求
        if request.method in ['GET', 'HEAD', 'OPTIONS']:
            return True
            
        # 允许管理员用户进行所有操作
        return request.user and hasattr(request.user, 'role') and request.user.role == 1 